package com.itheima.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    private static AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request  = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求的URI
        String uri = request.getRequestURI();
        log.info("本次拦截到的请求:{}",uri);
        //判断本次请求是否需要处理
        String[] urls = {
                "/css/**",
                "/fonts/**",
                "/img/**",
                "/plugins/**",
                "/pages/login.html",
                "/validateCode/send4Login.do",
                "/member/login.do"
        };
        boolean match = false;
        for (String url : urls) {
            match = antPathMatcher.match(url,uri);
            if (match){
                //放行请求,如果不需要处理,直接放行
                filterChain.doFilter(request,response);
                return;
            }
        }
        //获得用户登录信息
        HttpSession session = request.getSession();
        Integer memberId = (Integer) session.getAttribute("memberId");
        if (memberId == null){//代表没有登录，正常拦截跳转到登录页面
            //如果未登录则返回未登录结果  跳转登录页面
            response.sendRedirect("/pages/login.html");
            return;
        }
        filterChain.doFilter(request,response);
        return;
    }
}
